package org.ewicom.ppsaddressbook.model;

import java.util.ArrayList;
import java.util.List;

import org.ewicom.ppsaddressbook.DatabaseHelper;
import org.ewicom.ppsaddressbook.PPSAddressBook.UnitColumns;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class UnitDataSource {

	private SQLiteDatabase db;
	private DatabaseHelper dbHelper;

	private static final String[] UNIT_PROJECTION = new String[] {
			UnitColumns._ID, UnitColumns.NAME, UnitColumns.SHORT_NAME,
			UnitColumns.STREET, UnitColumns.CITY,
			UnitColumns.PHONE, UnitColumns.EMAIL, };

	private static final int COLUMN_INDEX_UNIT_ID = 0;
	private static final int COLUMN_INDEX_UNIT_NAME = 1;
	private static final int COLUMN_INDEX_UNIT_SHORT_NAME = 2;
	private static final int COLUMN_INDEX_UNIT_STREET = 3;
	private static final int COLUMN_INDEX_UNIT_CITY = 4;
	private static final int COLUMN_INDEX_UNIT_PHONE = 5;
	private static final int COLUMN_INDEX_UNIT_EMAIL = 6;

	public UnitDataSource(Context context) {
		dbHelper = new DatabaseHelper(context);
	}

	public void open() throws SQLException {
		db = dbHelper.getReadableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public Unit getUnitById(long id) {
		Cursor cursor = db.query(UnitColumns.UNIT_TABLE_NAME, UNIT_PROJECTION,
				UnitColumns._ID + "=" + String.valueOf(id), null, null, null,
				UnitColumns.DEFAULT_SORT_ORDER);

		cursor.moveToFirst();
		if (cursor.getCount() > 0) {
			Unit unit = cursorToUnit(cursor);
			cursor.close();
			return unit;
		}

		cursor.close();
		return null;
	}

	public List<Unit> getAllUnits() {
		List<Unit> units = new ArrayList<Unit>();

		Cursor cursor = db.query(UnitColumns.UNIT_TABLE_NAME, UNIT_PROJECTION,
				null, null, null, null, UnitColumns.DEFAULT_SORT_ORDER);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Unit unit = cursorToUnit(cursor);
			units.add(unit);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return units;
	}

	private Unit cursorToUnit(Cursor cursor) {
		Unit unit = new Unit();

		unit.setId(cursor.getLong(COLUMN_INDEX_UNIT_ID));
		unit.setName(cursor.getString(COLUMN_INDEX_UNIT_NAME));
		unit.setShortName(cursor.getString(COLUMN_INDEX_UNIT_SHORT_NAME));
		unit.setStreet(cursor.getString(COLUMN_INDEX_UNIT_STREET));
		unit.setCity(cursor.getString(COLUMN_INDEX_UNIT_CITY));
		unit.setPhone(cursor.getString(COLUMN_INDEX_UNIT_PHONE));
		unit.setEmail(cursor.getString(COLUMN_INDEX_UNIT_EMAIL));

		return unit;
	}
}
